package com.boruan.qq.zxgylibrary.service.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.ToastUtils;
import com.boruan.qq.zxgylibrary.MainActivity;
import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.base.BasePresenter;
import com.boruan.qq.zxgylibrary.base.BaseView;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.service.manager.DataManager;
import com.boruan.qq.zxgylibrary.service.manager.GXDrugModule;
import com.boruan.qq.zxgylibrary.service.model.FirstBannerBean;
import com.boruan.qq.zxgylibrary.service.model.FirstCategoryBean;
import com.boruan.qq.zxgylibrary.service.model.ResponseModel;
import com.boruan.qq.zxgylibrary.service.view.FirstPageView;
import com.boruan.qq.zxgylibrary.ui.activities.PharmacyHomePageActivity;
import com.boruan.qq.zxgylibrary.ui.widgets.CommonDialog;
import com.boruan.qq.zxgylibrary.utils.CallPhoneUtils;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;
import com.boruan.qq.zxgylibrary.utils.CustomDialogOne;
import com.convenient.qd.core.bean.BaseResBean;
import com.convenient.qd.core.bean.HomeResponse;
import com.convenient.qd.core.net.BaseHttpObserver;
import com.convenient.qd.core.net.RefuseHttpObserver;
import com.convenient.qd.core.user.UserDBHelper;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Subscriber;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.ResponseBody;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 崔琦 on 2019/8/19.
 * des: 首页逻辑持有者
 */

public class FirstPagePresenter implements BasePresenter{

    private Activity mContext;
    private FirstPageView firstPageView;
    private DataManager dataManager;

    /** 定位功能 */
    /** 声明AMapLocationClient类对象 */
    public AMapLocationClient mLocationClient = null;
    /** 声明定位回调监听器 */
    public AMapLocationListener mLocationListener;
    public AMapLocationClientOption mLocationOption = null;

    /** 首页banner数据对象 */
    private List<FirstBannerBean.ResultBean> mFirstBannerBean;
    /** 首页分类数据对象 */
    private List<FirstCategoryBean.ResultBean> mFirstCategoryBean;

    private CustomDialogOne customDialogOne;

    public FirstPagePresenter(Activity mContext) {
        this.mContext = mContext;
    }

    @Override
    public void onCreate() {
        dataManager = new DataManager(mContext);
        customDialogOne = new CustomDialogOne(mContext, R.style.CustomDialogOne);
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {
        firstPageView = null;
    }

    @Override
    public void pause() {

    }

    @Override
    public void attachView(BaseView view) {
        firstPageView = (FirstPageView) view;
    }

    /**
     * 进首页的时候定位地址
     *
     * @param tvLocation
     */

    public void startLocation(final TextView tvLocation, final int locationType) {//1的时候只定位，不上传经纬度，2：上传经纬度
        if (locationType == 1){
            customDialogOne.show();
        }

        //updateLocation(String.valueOf("36.002118"),String.valueOf("120.290013"));

        mLocationClient = new AMapLocationClient(mContext);
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null){
                    if (amapLocation.getErrorCode() == 0){
                        //定位成功回调信息，设置相关消息
                        ConstantInfo.lat = amapLocation.getLatitude();
                        ConstantInfo.lng = amapLocation.getLongitude();
                        Log.i("current" ,ConstantInfo.lat + "--" + ConstantInfo.lng);
                        /** 上传经纬度 */
                        if (locationType == 2){
                            updateLocationOne(String.valueOf(ConstantInfo.lat),String.valueOf(ConstantInfo.lng));
                        }

                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(amapLocation.getTime());
                        df.format(date);//定位时间
                        ConstantInfo.mCity = amapLocation.getCity();
                        amapLocation.getDistrict();//城区信息
                        Log.i("city",ConstantInfo.mCity);

                        ConstantInfo.mDistrict = amapLocation.getStreet() + amapLocation.getStreetNum();
                        tvLocation.setText(ConstantInfo.mDistrict);
                        if (locationType == 1){
                            customDialogOne.dismiss();
                        }
                    }else {
                        Log.e("AmapError","location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                        if (amapLocation.getErrorCode() == 4 || amapLocation.getErrorCode() == 18  || amapLocation.getErrorCode() == 19){
                            Toast.makeText(mContext, "网络未连接，请稍后重试！", Toast.LENGTH_SHORT).show();
                            mContext.finish();
                            return;
                        }
                        if (ConstantInfo.isDialogShow){
                            openGPSDialog();
                        }
                    }
                }
            }
        };
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        if(mLocationOption.isOnceLocationLatest()){
            mLocationOption.setOnceLocationLatest(true);
        }
        mLocationOption.setWifiActiveScan(true);
        mLocationOption.setMockEnable(false);
        mLocationOption.setInterval(2000);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    private void openGPSDialog() {
        new CommonDialog.Builder(mContext).setCanceledOnTouchOutside(false)
                .setTitle("请打开应用定位权限")
                .setMessage("为了提高定位的准确度，更好的为您服务，请打开GPS")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //跳转到手机打开GPS页面
                        ConstantInfo.isRestart = true;
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivityForResult(intent,887);
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContext.finish();
            }
        }).show();

    }

    /**
     * 获取首页banner图
     * */
    public void getFirstBannerData(){
        //统一网络请求
        GXDrugModule.getInstance().getFirstBanner(new BaseHttpObserver<BaseResBean<List<FirstBannerBean.ResultBean>>>() {
            @Override
            public void onSuccess(BaseResBean<List<FirstBannerBean.ResultBean>> firstBannerBean) {
                mFirstBannerBean = firstBannerBean.getResult();
                if (mFirstBannerBean != null){
                    firstPageView.getFirstBannerDataSuccess(mFirstBannerBean);
                }
            }

            @Override
            public void onFailure(int status, String msg) {
                firstPageView.getFirstBannerDataFailed(msg);
            }
        });
    }

    /**
     * 获取首页分类
     * */
    public void getFirstCategoryData(){
        GXDrugModule.getInstance().getFirstCategoryData(new BaseHttpObserver<BaseResBean<List<FirstCategoryBean.ResultBean>>>() {
            @Override
            public void onSuccess(BaseResBean<List<FirstCategoryBean.ResultBean>> firstCategoryBean) {
                mFirstCategoryBean = firstCategoryBean.getResult();
                if (mFirstCategoryBean != null){
                    firstPageView.getFirstCategoryDataSuccess(mFirstCategoryBean);
                }
            }

            @Override
            public void onFailure(int status, String msg) {
                firstPageView.getFirstCategoryDataFailed(msg);
            }
        });
    }

    /**
     * 上传首页经纬度
     * */
    public void updateLocation(String lat,String lon){
        Log.i("latlon",lat + "--" + lon);

        GXDrugModule.getInstance().saveUpdateLocation(lat, lon, new BaseHttpObserver<BaseResBean<ResponseModel>>() {
            @Override
            public void onSuccess(BaseResBean<ResponseModel> body) {
                Log.i("body",body.getMessage());
            }

            @Override
            public void onFailure(int status, String msg) {
                if (status == 200){
                    firstPageView.saveLocationSuccess(msg);
                }else {
                    firstPageView.saveLocationFailed(msg);
                }
            }
        });

    }


    private String locationJson;
    public void updateLocationOne(String lat,String lon){
        GXDrugModule.getInstance().saveUpdateLocationOne(lat,lon,new RefuseHttpObserver<ResponseBody>(){

            @Override
            public void onSuccess(ResponseBody body) {
                try {
                    locationJson = body.string();
                    Log.i("locationJson",locationJson);
                    firstPageView.saveLocationSuccess(new Gson().toJson(locationJson));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int status, String msg) {
                if (status == 200){
                    firstPageView.saveLocationSuccess(msg);
                }else {
                    firstPageView.saveLocationFailed(msg);
                }
            }
        });
    }
}
